import os
import time, json
import pyautogui as pg
import pyperclip as pc
from datetime import datetime
from dateutil.relativedelta import relativedelta

# 操作间隔为1秒
pg.PAUSE = 1
log = open('logs.log', 'a', encoding='utf-8')
file = open('settings/config.json', 'r', encoding='utf-8')
data = json.loads(file.read())
name = data['nick']
msg = data['content']
weekday = datetime.now().isoweekday()
if weekday <= 5:
    send_time = data['workday']
else:
    send_time = data['unworkday']


def main():
    # 打开微信
    pg.hotkey('ctrl', 'alt', 'w')
    time.sleep(1)
    for user, message in zip(name, msg):
        pg.hotkey('ctrl', 'f')

        # 找到消息发送对象
        pc.copy(user)
        pg.hotkey('ctrl', 'v')
        pg.press('enter')

        # 发送消息
        pc.copy(message)
        pg.hotkey('ctrl', 'v')
        pg.press('enter')

    # 隐藏微信
    pg.hotkey('ctrl', 'alt', 'w')


# 时段模式
def time_mode():
    # 循环获取当前时间，如果为指定时间我们将调用main函数为女朋友发送晚安消息
    while True:
        hour = time.localtime()
        now_time = time.strftime("%H:%M:%S", hour)
        log_time = time.strftime("%Y-%m %H:%M:%S", hour)
        # print(f'\r{now_time}')
        # 如果时间为半夜12点，则给女朋友发消息
        if now_time in send_time:
            info = f'【Time：{log_time}，Msg:{msg}】'.center(50, '=')
            print(info)
            main()
            log.write(info + '\n')


# 倒计时模式
def second_mode():
    currrent_date = datetime.now()
    while True:
        n_date = datetime.now()
        now_date = n_date.strftime('%Y-%m-%d %H:%M')
        # send_date = currrent_date + relativedelta(minutes=int(data['minutes']), hours=int(data['hour']))
        s_date = currrent_date.strftime(f'%Y-%m-%d %H:{(currrent_date.minute + int(data["minutes"])) % 60:02d}')
        print(f'\r当前时间：{now_date} 消息发送时间：{s_date}', end='')

        # 如果当前时间等于发消息时间则开始发消息
        if now_date == s_date:
            currrent_date = datetime.now()
            main()
            info = f'【Time：{now_date}\tReceive:{data["nick"]}\tMsg:{msg}】'.center(50, '=')
            log.writelines(info)
            print('\n', info)
            os.system('cls')

        # print(f'\r', end='')

        time.sleep(1)


def work():
    print('Running……'.center(50, ' '))
    print('-'.center(50, '-'))
    mode = data['mode']
    if mode == '时段模式':
        time_mode()
    elif mode == '倒计时模式':
        second_mode()
